<?php

namespace app\api\controller;

 
use think\App;
use \app\admin\traits\Curd;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Env;
use WeChat\Pay;
class Notify 
{

    // protected $noNeedLogin = ['wechat_notify'];
    // protected $mustLogin = ['wechat_notify'];

    protected $wechat_config = [];
    // protected $allowModifyFileds = ['username', 'sort', 'status_text'];

    // use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        $this->wechat_config = [
            // 'token'          => 'test',
            'appid'          => Env::get('pay.appid'),
            'appsecret'      => '',
            'encodingaeskey' => '',
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id'         => Env::get('pay.mchid'),
            'mch_key'        => Env::get('pay.apikey'),
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key'        => root_path().'/cert/apiclient_key.pem',
            'ssl_cer'        => root_path().'/cert/apiclient_cert.pem',
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path'     => '',
        ];
        // parent::__construct($app);
        // $this->model = new ModelOrder();

    }

    /**
     * 订单支付
     */
    public function wechat_notify()
    {
       file_put_contents('jinquno.log', "进入回调".PHP_EOL, FILE_APPEND);
       $wechat = \WeChat\Pay::instance($this->wechat_config);
       $data = $wechat->getNotify();
        file_put_contents('jinquno.log', date('Y-m-d H:i:s').':'.json_encode($data).PHP_EOL, FILE_APPEND);
       if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
           // @todo 去更新下原订单的支付状态
           $order_no = $data['out_trade_no'];
           $attach = $data['attach'];
           if ($attach == 1) {
              $ret = $this->order_fun($order_no, $data);
           }
           ob_clean();
           if ($ret){
             echo $wechat->getNotifySuccessReply();
            //  echo '<xml>
            //     <return_code><![CDATA[SUCCESS]]></return_code>
            //     <return_msg><![CDATA[OK]]></return_msg>
            //     </xml>';
           }
       }
    }

    //人脸验证回调
    public function returnurl_notify(){
        $data = $_GET;
        $uid = $data["uid"];
        $response = json_decode($data["response"],true);
        $code = $response["code"];
        $extInfo = $response["extInfo"];
        $certifyId = $extInfo["certifyId"];
        file_put_contents('jinquno.log', date('Y-m-d H:i:s').'进入回调999:'.json_encode($data).PHP_EOL, FILE_APPEND);

        //根据uid修改用户客户端认证结果
        Db::name("user")->where("id",$uid)->update(["certifyId"=>$certifyId,"code"=>$code]);
    
        // if($code == 1000){

        //     $qaa = DescribeFaceVerify::main(["certifyId"=>$certifyId,"sceneId"=>1000010413]);

        // }
       
     

    }
 
    public function order_fun($order_no, $data)
    {
        $order_record = Db::name('order_record')->where('new_order_no',$order_no)->find();
        $order = Db::name('order')->where('order_no',$order_record['order_no'])->where('status',1)->find();
        file_put_contents('jinquno.log', date('Y-m-d H:i:s').'进入回调222:'.json_encode($order).PHP_EOL, FILE_APPEND);
        if (!empty($order)) {
           $transaction_id = $data['transaction_id'];
           $up_data = ["pay_time" => time(), "transaction_id" => $transaction_id,'status'=>2,'paidin_money'=>$order['payable_money']];
           Db::name('order')->where('order_no', $order_record['order_no'])->where('status', 1)->update($up_data);
           file_put_contents('jinquno.log', date('Y-m-d H:i:s').'qwe====qwe:'.json_encode($up_data).PHP_EOL, FILE_APPEND);
           $user = Db::name("user")->where("id",$order["uid"])->find();
           if($user["is_mermber"] != 1){
                //修改用户余额
                Db::name("user")->where("id",$order["uid"])->inc("balance",$order["payable_money"])->update();
                Db::name("user")->where("id",$order["uid"])->update(["is_mermber"=>1,"level"=>$order["level"]]);
           }else{
               //分销商佣金比例
               $one_bili = bcdiv(sysconfig("commissoin","one_bili"),100,2);
               $two_bili = bcdiv(sysconfig("shopfx","two_bili"),100,2);
               //查询上一级
               if(!empty($user["pid"])){
                   //给上一级返回佣金
                   $puser = Db::name("user")->where("id",$user["pid"])->find();
                   $user_commission = bcmul($one_bili,$order["paidin_money"],2);
                   Db::name("user")->where("id",$user["pid"])->inc("commission",$user_commission)->update();
                   //加入记录
                   Db::name("user_commrecord")->insert([
                       "oid"=>$order["id"],
                       "uid"=>$order["uid"],
                       "pid"=>$user["pid"],
                       "user_commoney"=>$puser["commission"],
                       "return_commission"=>$user_commission,
                       "create_time"=>time()
                   ]);
               }
               //给上二级返回佣金
               $pyiuser = Db::name("user")->where("id",$user["pid"])->find();
               $pyiuser_commission = bcmul($two_bili,$order["paidin_money"],2);
               if(!empty($pyiuser["pid"])){
                   Db::name("user")->where("id",$pyiuser["pid"])->inc("commission",$pyiuser_commission)->update();
                   //加入记录
                   Db::name("user_commrecord")->insert([
                       "oid"=>$order["id"],
                       "uid"=>$order["uid"],
                       "pid"=>$pyiuser["pid"],
                       "user_commoney"=>$pyiuser["commission"],
                       "return_commission"=>$pyiuser_commission,
                       "create_time"=>time()
                   ]);
               }
   
           }
           
        } else {
            return false;
        }
        return true;
    }


     /**
     * 打赏订单支付
     */
    public function reward_notify()
    {
       file_put_contents('dashang.log', "进入回调".PHP_EOL, FILE_APPEND);
       $wechat = \WeChat\Pay::instance($this->wechat_config);
       $data = $wechat->getNotify();
        file_put_contents('dashang.log', date('Y-m-d H:i:s').':'.json_encode($data).PHP_EOL, FILE_APPEND);
       if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
           // @todo 去更新下原订单的支付状态
           $order_no = $data['out_trade_no'];
           $attach = $data['attach'];
           if ($attach == 1) {
              $ret = $this->order_price_difference($order_no, $data);
           }
           ob_clean();
           if ($ret){
             echo $wechat->getNotifySuccessReply();
           }
       }
    }

    public function order_price_difference($order_no, $data)
    {
        $order_record = Db::name('order_record')->where('new_order_no',$order_no)->where('type',1)->find();
        $order = Db::name('order_price_difference')->where('sub_order_no',$order_record['order_no'])->where('status',0)->find();
        file_put_contents('dashang.log', date('Y-m-d H:i:s').'进入回调打赏:'.json_encode($order).PHP_EOL, FILE_APPEND);
        if (!empty($order)) {
           $transaction_id = $data['transaction_id'];
           $up_data = ["pay_time" => time(), "transaction_id" => $transaction_id,'status'=>1];
           Db::name('order_price_difference')->where('sub_order_no', $order_record['order_no'])->where('status', 0)->update($up_data);
           file_put_contents('dashang.log', date('Y-m-d H:i:s').'up_data:'.json_encode($up_data).PHP_EOL, FILE_APPEND);
           //修改达人余额
           Db::name("service_technician")->where("id",$order["service_technician_id"])->inc("balance",$order["money"])->update();
        } else {
            return false;
        }
        return true;
    }



      /**
     * @desc 该方法向用户发送预约成功通知
     * @param $openid 接收消息用户的openid
     * @param $arr 消息内容，根据模板需要进行配置
     */
    public function real_authentication($openid,$arr){
            $template_id = "Jdr1nGIVy-BpYyR8slvtvZebxio5AetQKjpYqht9Z-0";
            $template = "{
                \"touser\": \"{$openid}\",
                \"template_id\": \"{$template_id}\",
                \"page\": \"pages/self_appoint/self_appoint\",
                \"miniprogram_state\":\"developer\",
                \"lang\":\"zh_CN\",
                \"data\": {
                    \"character_string6\": {
                        \"value\": \"{$arr['order_no']}\"
                    },
                    \"thing7\": {
                        \"value\": \"{$arr['title']}\"
                    },
                    \"character_string8\": {
                        \"value\": \"{$arr['time_start']}\"
                    },
                    \"amount9\": {
                        \"value\": \"{$arr['payable_money']}\"
                    },
                    \"thing2\": {
                        \"value\": \"{$arr['address']}\"
                    }
                }
              }";
          //获取access_token
          $access_token = $this->get_access_token();
          //使用curl进行请求
          $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";
          $res = $this->curl_post($url,$template);
          return $res;
    }
  
    //curl请求的方法
    private function curl_post($url,$data=array()){
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
          // POST数据
          curl_setopt($ch, CURLOPT_POST, 1);
          // 把post的变量加上
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
          $output = curl_exec($ch);
          curl_close($ch);
          return $output;
      }
      /**
       * @desc 获取access_token
       */
      private function get_access_token(){
      
      $appid = 'wx6e95e7efa60d658d';
      $secretkey = '6211a9823ba64c8f839b1d3b1419d3bf';
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secretkey ;
      $res = json_decode(file_get_contents($url),true);//获取微信返回的access_token
      $access_token = $res['access_token'];
      //获取到access_token应该保存起来，一般7000秒内不会过期
      Cache::set('accessToken',$access_token, 5400);
      return Cache::get('accessToken');
  }
 

}
